package com.example.skudemo.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.skudemo.core.exception.CommonException;
import com.example.skudemo.dto.SkuBaseDTO;
import com.example.skudemo.dto.SpuDTO;
import com.example.skudemo.model.SkuEntity;
import com.example.skudemo.model.SpuEntity;
import com.example.skudemo.service.ISkuService;
import com.example.skudemo.service.ISpuService;
import com.example.skudemo.utils.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 商品spu表 前端控制器
 * </p>
 *
 * @author 水痕
 * @since 2023-11-17
 */
@RestController
@Slf4j
@Validated
@RequestMapping("/spu")
public class SpuController {
    @Autowired
    private ISpuService spuService;

    @Autowired
    private ISkuService skuService;

    @PostMapping
    @Transactional
    public ApiResult createSpuApi(@RequestBody @Valid SpuDTO req) {
        // 判断是否为多规格模式
        if (req.getSpecType().equals(1) && req.getSkuList().isEmpty()) {
            throw new CommonException("当前是多规格模式,sku不能为空");
        }
        // 单规格的时候
        SpuEntity spuEntity = BeanUtil.copyProperties(req, SpuEntity.class);
        if (req.getSpecType() == 0) {
            if (this.spuService.save(spuEntity)) {
                return ApiResult.success("创建成功");
            }
            return ApiResult.error("创建失败");
        }
        // 多规格的时候
        if (!this.spuService.save(spuEntity)) {
            log.error("插入spu失败");
            throw new CommonException("创建失败");
        }
        List<SkuEntity> skuEntities = new ArrayList<>();
        for (SkuBaseDTO item : req.getSkuList()) {
            SkuEntity skuEntity = BeanUtil.copyProperties(item, SkuEntity.class);
            skuEntity.setSpuId(spuEntity.getId());
            skuEntities.add(skuEntity);
        }
        if (!this.skuService.saveBatch(skuEntities)) {
            log.error("批量删除sku失败");
            throw new CommonException("创建失败");
        }
        return ApiResult.success("创建成功");
    }

    @GetMapping
    public ApiResult getSpuPageApi(
            @RequestParam(required = false, defaultValue = "1", name = "pageNumber")
            @Min(value = 1, message = "pageNumber最小为1") Integer pageNumber,
            @RequestParam(required = false, defaultValue = "10", name = "pageSize")
            @Min(value = 1, message = "pageSize最小为1") Integer pageSize
    ) {
        return this.spuService.getSpuPageApi(pageNumber, pageSize);
    }

    @GetMapping("{id}")
    public ApiResult getSpuByIdApi(@PathVariable Integer id) {
        LambdaQueryWrapper<SpuEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpuEntity::getId, id);
        SpuEntity spuEntity = this.spuService.getOne(queryWrapper);
        Optional.ofNullable(spuEntity).orElseThrow(() -> new CommonException("查不到数据"));
        return ApiResult.success(spuEntity);
    }
}
